package com.hbsoft.lms.service;

import com.hb.bean.CallResult;
import com.hb.util.BasePassUtil;
import com.hbsoft.common.constant.Constant;
import com.hbsoft.common.enumtype.AreaUserRoleEnum;
import com.hbsoft.common.enumtype.GetDingdingTypeEnum;
import com.hbsoft.lms.bean.*;
import com.hbsoft.lms.dao.service.*;
import com.hbsoft.lms.vo.DDUserVo;
import com.hbsoft.lms.vo.DepartmentVo;
import com.hbsoft.lms.vo.DictVo;
import com.hbsoft.util.DDUtil;
import com.hbsoft.util.GsonUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CustomerManagerService {


    @Autowired
    private BankBranchBeanDaoService bankBranchBeanDaoService;

    @Autowired
    private LoanUseBeanDaoService loanUseBeanDaoService;

    @Autowired
    private DdUserBeanDaoService ddUserBeanDaoService;

    @Autowired
    private DdDeptBeanDaoService ddDeptBeanDaoService;

    @Autowired
    private AreaUserBeanDaoService areaUserBeanDaoService;

    @Autowired
    private BankBeanDaoService bankBeanDaoService;

    @Autowired
    private HBUserService hbUserService;

    @Autowired
    private BankDingService bankDingService;

    @Autowired
    private BankDingTokenBeanDaoService bankDingTokenBeanDaoService;

    @Autowired
    private DdDeptAllBeanDaoService ddDeptAllBeanDaoService;


    public List<DictVo> getAllUserType() {
        List<DictVo> list = new ArrayList<>();
        DictVo vo = new DictVo();
        vo.setName("贷前");
        list.add(vo);
        vo = new DictVo();
        vo.setName("贷中");
        list.add(vo);
        vo = new DictVo();
        vo.setName("贷后");
        list.add(vo);
        vo = new DictVo();
        vo.setName("起诉");
        list.add(vo);
        vo = new DictVo();
        vo.setName("主营");
        list.add(vo);
        vo = new DictVo();
        vo.setName("领导");
        list.add(vo);
        vo = new DictVo();
        vo.setName("档案");
        list.add(vo);
        return list;
    }

    public List<DictVo> getAllBankBranchBean(BankBranchBean bankBranchBean) throws Exception {
        List<BankBranchBean> list = bankBranchBeanDaoService.getAll(bankBranchBean);
        List<DictVo> voList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (BankBranchBean bb : list) {
                DictVo vo = new DictVo();
                vo.setName(bb.getName());
                vo.setCode(bb.getCode());
                voList.add(vo);
            }
        }
        return voList;
    }

    public List<DictVo> getAllLoanUse(LoanUseBean loanUseBean) throws Exception {
        List<LoanUseBean> list = loanUseBeanDaoService.getAll(loanUseBean);
        List<DictVo> voList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (LoanUseBean lb : list) {
                DictVo vo = new DictVo();
                vo.setCode(lb.getId());
                vo.setName(lb.getName());
                voList.add(vo);
            }
        }
        return voList;
    }

    @Transactional
    public CallResult<String> updateDdInfo(String bankCode, String deptIdParam) throws Exception {
        CallResult<String> callResult = new CallResult<>();
        if (StringUtils.isBlank(deptIdParam)) {


            BankDingTokenBean dingToken = new BankDingTokenBean();
            dingToken.setBankCode(bankCode);
            BankDingTokenBean bankDingTokenBean = bankDingTokenBeanDaoService.getByField(dingToken);

            if (GetDingdingTypeEnum.GETDING_TYPE_PART.getCode().equals(bankDingTokenBean.getGetDdType())) {
                DdDeptAllBean ddparam = new DdDeptAllBean();
                ddparam.setId(bankDingTokenBean.getDdDeptId());
                DdDeptAllBean byField = ddDeptAllBeanDaoService.getByField(ddparam);
                if(byField != null){
                    DdDeptBean record = new DdDeptBean();
                    record.setBankCode(bankCode);
                    record.setId(byField.getId());
                    record.setName(byField.getName());
                    record.setPid(byField.getPid());
                    DdDeptBean ddDeptBean = ddDeptBeanDaoService.getByField(record);
                    if(ddDeptBean != null){
                        record.setId_prikey(ddDeptBean.getId_prikey());
                        ddDeptBeanDaoService.set(record);
                    }else{
                        ddDeptBeanDaoService.add(record);
                    }
                }
                CallResult<DDUserVo> ddUseResult = bankDingService.getBankDingUserFromInterface(bankCode, bankDingTokenBean.getDdDeptId());
                if (ddUseResult.isExec()) {
                    List<DdUserBean> ddUserList = ddUseResult.getData().getUserlist();
                    for (DdUserBean user : ddUserList) {
                        user.setActive("true".equals(user.getActive()) ? "1" : "0");
                        user.setIsAdmin("true".equals(user.getIsAdmin()) ? "1" : "0");
                        user.setIsBoss("true".equals(user.getIsBoss()) ? "1" : "0");
                        user.setIsHide("true".equals(user.getIsHide()) ? "1" : "0");
                        user.setIsLeader("true".equals(user.getIsLeader()) ? "1" : "0");
                        user.setDeptId(bankDingTokenBean.getDdDeptId());
                        user.setBankCode(bankCode);
                        user.setUpdateOn(new Date());
                        DdUserBean param = new DdUserBean();
                        param.setUserid(user.getUserid());
                        param.setDeptId(bankDingTokenBean.getDdDeptId());
                        param.setBankCode(bankCode);
                        DdUserBean ddUserBean = ddUserBeanDaoService.getByField(param);
                        if (ddUserBean != null) {
                            user.setId_prikey(ddUserBean.getId_prikey());
                            ddUserBeanDaoService.set(user);
                        } else {
                            ddUserBeanDaoService.add(user);
                        }
                    }
                }
            } else if (GetDingdingTypeEnum.GETDING_TYPE_ALL.getCode().equals(bankDingTokenBean.getGetDdType())) {
                CallResult<DepartmentVo> deptResult = bankDingService.getBankDingDeptFromInterface(bankCode);
                if (deptResult.isExec()) {
                    List<DdDeptBean> deptList = deptResult.getData().getDepartment();
                    for (DdDeptBean dept : deptList) {
                        DdDeptBean deptParam = new DdDeptBean();
                        deptParam.setId(dept.getId());
                        deptParam.setBankCode(bankCode);
                        DdDeptBean ddDeptBean = ddDeptBeanDaoService.getByField(deptParam);
                        if (ddDeptBean != null) {
                            ddDeptBean.setPid(dept.getParentid());
                            ddDeptBean.setName(dept.getName());
                            ddDeptBean.setBankCode(bankCode);
                            ddDeptBeanDaoService.set(ddDeptBean);
                        } else {
                            dept.setBankCode(bankCode);
                            dept.setPid(dept.getParentid());
                            ddDeptBeanDaoService.add(dept);
                        }
                        CallResult<DDUserVo> ddUseResult = bankDingService.getBankDingUserFromInterface(bankCode, dept.getId());
                        if (ddUseResult.isExec()) {
                            List<DdUserBean> ddUserList = ddUseResult.getData().getUserlist();
                            for (DdUserBean user : ddUserList) {
                                user.setActive("true".equals(user.getActive()) ? "1" : "0");
                                user.setIsAdmin("true".equals(user.getIsAdmin()) ? "1" : "0");
                                user.setIsBoss("true".equals(user.getIsBoss()) ? "1" : "0");
                                user.setIsHide("true".equals(user.getIsHide()) ? "1" : "0");
                                user.setIsLeader("true".equals(user.getIsLeader()) ? "1" : "0");
                                user.setDeptId(dept.getId());
                                user.setBankCode(bankCode);
                                user.setUpdateOn(new Date());
                                DdUserBean param = new DdUserBean();
                                param.setUserid(user.getUserid());
                                param.setDeptId(dept.getId());
                                param.setBankCode(bankCode);
                                DdUserBean ddUserBean = ddUserBeanDaoService.getByField(param);
                                if (ddUserBean != null) {
                                    user.setId_prikey(ddUserBean.getId_prikey());
                                    ddUserBeanDaoService.set(user);
                                } else {
                                    ddUserBeanDaoService.add(user);
                                }
                            }
                        }
                    }
                }
            }
        } else {
            CallResult<DDUserVo> ddUseResult = bankDingService.getBankDingUserFromInterface(bankCode, deptIdParam);
            if (ddUseResult.isExec()) {
                List<DdUserBean> ddUserList = ddUseResult.getData().getUserlist();
                for (DdUserBean user : ddUserList) {
                    user.setActive("true".equals(user.getActive()) ? "1" : "0");
                    user.setIsAdmin("true".equals(user.getIsAdmin()) ? "1" : "0");
                    user.setIsBoss("true".equals(user.getIsBoss()) ? "1" : "0");
                    user.setIsHide("true".equals(user.getIsHide()) ? "1" : "0");
                    user.setIsLeader("true".equals(user.getIsLeader()) ? "1" : "0");
                    user.setDeptId(deptIdParam);
                    user.setBankCode(bankCode);
                    user.setUpdateOn(new Date());
                    DdUserBean param = new DdUserBean();
                    param.setUserid(user.getUserid());
                    param.setDeptId(deptIdParam);
                    param.setBankCode(bankCode);
                    DdUserBean ddUserBean = ddUserBeanDaoService.getByField(param);
                    if (ddUserBean != null) {
                        user.setId_prikey(ddUserBean.getId_prikey());
                        ddUserBeanDaoService.set(user);
                    } else {
                        ddUserBeanDaoService.add(user);
                    }
                }
            }
        }
        callResult.setCode(0);
        callResult.setMsg("操作成功");
        return callResult;
    }

    @Transactional
    public CallResult<String> addBankAreaAdmin(AreaUserBean areaUserBean, String user_id_prikey) throws Exception {
        CallResult<String> result = new CallResult<>();
        CallResult<String> passordVolidate = volidatePassword(areaUserBean.getPassword());
        if (!passordVolidate.isExec()) {
            return passordVolidate;
        }
        AreaUserBean param = new AreaUserBean();
        param.setTel(areaUserBean.getTel());
        AreaUserBean au = areaUserBeanDaoService.getByField(param);
        if (au != null) {
            result.setCode(400);
            result.setMsg("手机号已存在");
            return result;
        }
        areaUserBean.setRoleType("1");
        areaUserBean.setUpdateOn(new Date());
        areaUserBean.setCreateOn(new Date());
        areaUserBean.setCreateBy(user_id_prikey);
        areaUserBean.setUpdateBy(user_id_prikey);
        areaUserBeanDaoService.add(areaUserBean);
        //添加user
        CallResult<String> userresult = hbUserService.addHBUser(areaUserBean.getTel(), areaUserBean.getName(), areaUserBean.getPassword(), Constant.BANK);
        if (!userresult.isExec()) {
            throw new RuntimeException(userresult.getMsg());
        }
        result.setCode(0);
        result.setMsg("操作成功");
        return result;
    }

    @Transactional
    public CallResult<String> updateBankAreaAdmin(AreaUserBean areaUserBean, String user_id_prikey) throws Exception {
        CallResult<String> result = new CallResult<>();
        try {
            if (areaUserBean.getId_prikey() == null) {
                result.setCode(400);
                result.setMsg("参数有误");
                return result;
            }
            CallResult<String> passordVolidate = volidatePassword(areaUserBean.getPassword());
            if (!passordVolidate.isExec()) {
                return passordVolidate;
            }
            AreaUserBean au = areaUserBeanDaoService.getById(areaUserBean.getId_prikey());
            if (au != null) {
                if (!au.getTel().equals(areaUserBean.getTel())) {
                    AreaUserBean param = new AreaUserBean();
                    param.setTel(areaUserBean.getTel());
                    param.setRoleType(AreaUserRoleEnum.AREA_USER_ROLE_SHIB.getCode());
                    AreaUserBean auph = areaUserBeanDaoService.getByField(param);
                    if (auph != null) {
                        result.setCode(400);
                        result.setMsg("手机号已存在");
                        return result;
                    }
                    areaUserBean.setUpdateOn(new Date());
                    areaUserBean.setCreateOn(new Date());
                    areaUserBean.setCreateBy(user_id_prikey);
                    areaUserBean.setUpdateBy(user_id_prikey);
                    areaUserBeanDaoService.set(areaUserBean);
                    //添加user
                    CallResult<String> userresult = hbUserService.addHBUser(areaUserBean.getTel(), areaUserBean.getName(), areaUserBean.getPassword(), Constant.BANK);
                    if (!userresult.isExec()) {
                        throw new RuntimeException(userresult.getMsg());
                    }
                    result.setCode(0);
                    result.setMsg("操作成功");
                } else {
                    areaUserBean.setUpdateOn(new Date());
                    areaUserBean.setCreateOn(new Date());
                    areaUserBean.setCreateBy(user_id_prikey);
                    areaUserBean.setUpdateBy(user_id_prikey);
                    areaUserBeanDaoService.set(areaUserBean);
                    //更新User
                    CallResult<String> userresult = hbUserService.setHBuser(areaUserBean.getTel(), areaUserBean.getPassword());
                    if (!userresult.isExec()) {
                        throw new RuntimeException(userresult.getMsg());
                    }
                    result.setCode(0);
                    result.setMessage("操作成功");
                }
            } else {
                result.setCode(400);
                result.setMsg("参数有误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMsg("操作失败");
        }
        return result;
    }

    /**
     * 新建用户
     * 关联钉钉里部门和银行
     *
     * @param areaUserBean
     * @param user_id_prikey
     * @return
     */
    @Transactional
    public CallResult<String> addBankAdmin(AreaUserBean areaUserBean, String user_id_prikey) throws Exception {
        CallResult<String> result = new CallResult<>();
        CallResult<String> passordVolidate = volidatePassword(areaUserBean.getPassword());
        if (!passordVolidate.isExec()) {
            return passordVolidate;
        }
        BankBean bankParam = new BankBean();
        bankParam.setCode(areaUserBean.getCode());
        BankBean bankBean = bankBeanDaoService.getByField(bankParam);
        if (bankBean == null) {
            result.setCode(400);
            result.setMsg("code不存在");
            return result;
        }
        AreaUserBean param = new AreaUserBean();
        param.setTel(areaUserBean.getTel());
        param.setRoleType(AreaUserRoleEnum.AREA_USER_ROLE_Bank.getCode());
        AreaUserBean au = areaUserBeanDaoService.getByField(param);
        if (au != null) {
            result.setCode(400);
            result.setMsg("手机号已存在");
            return result;
        }
        areaUserBean.setRoleType("2");
        areaUserBean.setUpdateOn(new Date());
        areaUserBean.setCreateOn(new Date());
        areaUserBean.setCreateBy(user_id_prikey);
        areaUserBean.setUpdateBy(user_id_prikey);
        areaUserBeanDaoService.add(areaUserBean);
        //关联钉钉部门
       /* DdDeptBean deptParam = new DdDeptBean();
        deptParam.setId(areaUserBean.getDdDetpId());
        DdDeptBean ddDeptBean = ddDeptBeanDaoService.getByField(deptParam);
        if(ddDeptBean != null){
            //获取bankcode
            BankBean bankParam = new BankBean();
            bankParam.setCode(areaUserBean.getCode());
            BankBean bankInfo = bankBeanDaoService.getByField(bankParam);
            if(bankInfo != null){
                DdDeptBean record = new DdDeptBean();
                record.setId_prikey(ddDeptBean.getId_prikey());
                record.setBankCode(bankInfo.getBankCode());
                ddDeptBeanDaoService.set(record);
            }
        }*/
        // 添加user
        CallResult<String> userresult = hbUserService.addHBUser(areaUserBean.getTel(), areaUserBean.getName(), areaUserBean.getPassword(), Constant.BANKBRANCH);
        if (!userresult.isExec()) {
            throw new RuntimeException(userresult.getMsg());
        }
        result.setCode(0);
        result.setMsg("操作成功");
        return result;
    }


    public CallResult<String> volidatePassword(String password) {
        CallResult<String> result = new CallResult<>();
       /* if (!BasePassUtil.base64_decode(password).matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(.+)$")
                || BasePassUtil.base64_decode(password).length() < 8) {
            result.setCode(400);
            result.setMessage("密码设置必须有数字、大写字母和小写字母,密码长度不能少于8位");
            return  result;
        }*/
        result.setCode(0);
        return result;
    }
}
